﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Model.DbModels.Common;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.Security;
using TomNet.Web.Mvc.UI;

namespace TomNet.IMSC.Web.Controllers
{
    public class MenuController : BaseController
    {
        public IMenuContract MenuContract { get; set; }
		public Core.Contracts.Identity.IAuthorityContract AuthorityContract { get; set; }

        [Description("菜单-主页")]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 物业公司树
        /// </summary>
        /// <returns></returns>
        [Description("菜单-树列表")]
        [HttpPost, AjaxOnly]
        public ActionResult InitTreeAsync()
        {

            var data = MenuContract.Entities.Where(m => m.ParentID.Equals(0)).Select(m => new
            {
                id=m.Id,
                text=m.Text,

                children = MenuContract.Entities.Where(n => n.ParentID.Equals(m.Id)).Select(n => new
                {
                    id=n.Id,
                    text=n.Text,
                    children = MenuContract.Entities.Where(t => t.ParentID.Equals(n.Id)).Select(t => new
                    {
                        id = t.Id,
                        text = t.Text
                    })
                })
            }).ToList();

            return JsonEx(new
            {
                id = "0",
                text = "全部",
                children = data
            });
        }

        [Description("菜单-详细信息")]
        [HttpPost, AjaxOnly]
        public ActionResult ContracListAsync(int pageIndex, int pageSize, string search = "", int treeId = 0)
        {
            var query = MenuContract.Entities.Where(m => m.Id.Equals(treeId));
                        
            //数据总数
            var total = query.Count();
            
            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query : Enumerable.Empty<Menu>().AsQueryable();

            //此处可以采用匿名对象 GridData<object>
            GridData<object> gridData = new GridData<object>()
            {
                Total = total,
                Rows = query.Select(m => new
                {
                    id = m.Id,
                    text = m.Text,
                    title = m.Title,
                    url = m.Url
                }).ToList()
            };

            //此处采用重写后的jsonResult
            return JsonEx(gridData);

        }

        [Description("菜单-添加")]
        public ActionResult Insert()
        {
			//if (login.Authority == 3)
			//{
			//    Response.Redirect("Error/Unauthorized");
			//}

			//权限
			List<SelectListItem> items = new List<SelectListItem>();
			items.Add(new SelectListItem() { Text = "无", Value = "" });
			List<Model.DbModels.Identity.Authority> infosAuth = AuthorityContract.Entities.ToList();
			foreach(Model.DbModels.Identity.Authority info in infosAuth)
			{
				items.Add(new SelectListItem() { Text = info.Name, Value = info.Id.ToString() });
			}
			ViewData["selectAuth"] = new SelectList(items, "Value", "Text");

			return View();
        }
        [Description("菜单-添加")]
        [HttpPost, AjaxOnly]
        public ActionResult InsertAsync(Menu entity)
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                var query = MenuContract.CheckExists(m => m.Text.Equals(entity.Text) || m.Title.Equals(entity.Title));
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同名称的菜单";
                }
                else
                {
                    var count = MenuContract.Insert(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "录入成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "录入失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("楼盘-编辑")]
        public ActionResult Edit(int id)
        {
            //if (login.Authority == 3)
            //{
            //    Response.Redirect("Error/Unauthorized");
            //}
            var entity = MenuContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewData["entity"] = entity;
            if (entity.ParentID == 0)
            {
                ViewData["parentName"] = "全部";
            }
            else
            {
                var parent = MenuContract.GetByKey(entity.ParentID);
                if (parent == null) throw new Exception("未找到该实体");
                ViewData["parentName"] = parent.Text;
            }

			//权限
			List<SelectListItem> items = new List<SelectListItem>();
			items.Add(new SelectListItem() { Text = "无", Value = "" });
			List<Model.DbModels.Identity.Authority> infosAuth = AuthorityContract.Entities.ToList();
			foreach (Model.DbModels.Identity.Authority info in infosAuth)
			{
				items.Add(new SelectListItem() { Text = info.Name, Value = info.Id.ToString() });
			}
			ViewData["selectAuth"] = new SelectList(items, "Value", "Text", entity.AuthorityID);

			return View();
        }
        [Description("楼盘-编辑")]
        [HttpPost, AjaxOnly]
        public ActionResult EditAsync(Menu entity)
        {
            var result = new AjaxResult();
            try
            {
                var query = MenuContract.CheckExists(m => (m.Text.Equals(entity.Text) || m.Title.Equals(entity.Title)) && m.Id != entity.Id);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同名称的菜单";
                }
                else
                {
                    var count = MenuContract.Update(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "修改成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "修改失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("楼盘-删除")]
        [HttpPost, AjaxOnly]
        public ActionResult DeleteAsync(int id)
        {
            var result = new AjaxResult();
            try
            {
                if (MenuContract.Entities.Any(m => m.ParentID.Equals(id)))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "当前菜单存在子级，不能删除";
                }
                else
                {
                    var count = MenuContract.Delete(id);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "删除成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "删除失败";
                    }
                }

            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }


    }
}